﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using FtpWorkerRole.FtpServer;
using FtpWorkerRole.AzureStorage;

namespace FtpWorkerRole.FtpCommand
{
    class StorCommand : CommandBase
    {
        private const int bufferSize = 32768;
        public StorCommand(FtpSocketHandler handler)
            :base(handler)
        {
            commandName = "STOR";
        }

        public override void execute(string value)
        {
            if (!handler.Login)
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(530, "Please Login!"));
                return;
            }
            string path = Path.Combine(handler.currentDirectory, value);
            if (handler.fileSystem.isFileExist(path))
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(553, "File already exist"));
                return;
            }

            var file = handler.fileSystem.openFile(path, false);
            
            Utils.sendMessage(handler.getSocket(), formatMessage(150,"Openning Channel Socket"));
            DataSocketHandler dataHandler = new DataSocketHandler(handler);
            if (dataHandler.open())
            {
                byte[] data = new byte[bufferSize];
                int received = dataHandler.readData(data);
                while (received > 0)
                {
                    file.Write(data, received);
                    received = dataHandler.readData(data);
                }

                handler.fileSystem.put(path, file);
                file.Close();
                dataHandler.close();
                Utils.sendMessage(handler.getSocket(), formatMessage(226, "Transfer Complete"));
            }
            else
            {
            }
        }
    }
}
